<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\DefaultValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class CategoryExport extends DefaultValueBinder implements WithHeadings, WithCustomValueBinder, FromArray, WithStyles
{
    protected $data;

    public function __construct(array $data)
    {
        return $this->data = $data;
    }

    public function array(): array
    {
        $arr = [];
        foreach ($this->data as $item) {
            $dataItem = [
                $item['id'],
                $item['title'],
                $item['created_at'],
                $item['view_num'],
            ];
            $arr[] = $dataItem;
        }
        return $arr;
    }

    public function headings(): array
    {
        return [
            'id' => 'id',
            'title' => '名称',
            'created_at' => '创建时间',
            'view_num' => '浏览总数',
        ];
    }

    /**
     * @throws Exception
     */
    public function bindValue(Cell $cell, $value)
    {
        $column = $cell->getColumn();
        if (in_array($column, ['A', 'C', 'D'])) {
            try {
                // 根据传入的数据类型，会对数据转换格式
                $cell->setValueExplicit($value, DataType::TYPE_STRING);
            } catch (\Exception $e) {
            }
            return true;
        }
        return parent::bindValue($cell, $value);
    }

    public function styles(Worksheet $sheet)
    {
        $sheet->getDefaultRowDimension()->setRowHeight(22); // 设置行高
        $sheet->getColumnDimension('C')->setWidth(30); // 设置列宽
        // 设置整列格式
        $columns = ['A', 'B', 'C', 'D'];
        foreach ($columns as $column) {
            $sheet->getStyle($column)->getAlignment()->setVertical('center');
            $sheet->getStyle($column)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
            $sheet->getStyle($column)->applyFromArray([
                'alignment' => [
                    'horizontal' => 'left'
                ]
            ]);
        }
    }
}
